﻿/*******************************************************************************
* 
*Author         :  VN
*Description    :  网络通信模块多线程发包类
*Other          :  none
*Modify Record  :  none
*
*******************************************************************************/

using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System;
using System.IO;
using UnityEngine;

namespace Network
{
    class SenderThread : NetThread
    {
        struct tCache
        {
            public int nSize;
            public byte[] buffer;
        }

        const int MAX_LEN_CLI_PKG_DATA = 65536;
        private Queue m_ThreadSafeQueue;

        public SenderThread(NetworkStream stream)
            : base(stream)
        {
            m_ThreadSafeQueue = Queue.Synchronized(new Queue());
        }

        /*************************************************
        Description : 将包体放入发包队列
        Input       : pkg   包体
        Output      : none
        Return      : none
        Others      : none
        *************************************************/
        public void Send(byte[] buf , int nSize)
        {
            if (nSize > MAX_LEN_CLI_PKG_DATA)
            {
                if (RunMode.Instance.LogNetwork) Debug.LogError("Send.PackError. buf=" + buf.ToString() + "nSize=" + nSize.ToString());
                return;
            }

            tCache cache;
            cache.nSize = nSize;
            cache.buffer = buf;
            lock (m_ThreadSafeQueue)
            {
                m_ThreadSafeQueue.Enqueue(cache);
            }
        }

        /*************************************************
        Description : 发包线程主函数
        Input       : none
        Output      : none
        Return      : none
        Others      : none
        *************************************************/
        protected override void Main()
        {
            if (RunMode.Instance.LogNetwork) Debug.Log("SenderThread.Main : Begin");
            while (!IsTerminateFlagSet())
            {
                if (m_ThreadSafeQueue.Count <= 0)
                {
                    Thread.Sleep(15);
                    continue;
                }

                lock (m_ThreadSafeQueue)
                {
                    tCache cache = (tCache)m_ThreadSafeQueue.Dequeue();
                    NetStream.Write(cache.buffer, 0, cache.nSize);
                    NetStream.Flush();
                }
            }
            if (RunMode.Instance.LogNetwork) Debug.Log("SenderThread.Main : End");
        }
    }
}
